<!--  -->
<template>
  <div class="script_render">
    <el-form v-for="(scriptItem,i) in showJson"
             :key="i"
             :model="dataForm"
             :label-position="scriptItem.labelPosition?scriptItem.labelPosition:'top'"
             ref="dataForm"
             :class="scriptItem.itemClass?scriptItem.itemClass:''">
      <el-form-item :label="scriptItem.label"
                    :class="scriptItem.formClass || ''"
                    :rules="scriptItem.rules"
                    :prop="scriptItem.text"
                    :label-width="scriptItem.labelWidth?scriptItem.labelWidth:'90'"
                    :style="{ marginBottom: scriptItem.type === 'form-hidden' ? 0 : '10px' }">
        <span v-if="scriptItem.label"
              slot="label">
          <span class="span-box"
                v-if="scriptItem.text==='utilizationLower'"><span>{{$t('custom.bots.utilization1')}}</span>
            <TypeNumberInput :scriptItem='inputObj'
                             :dataForm='dataForm' />
            <span>{{$t('custom.bots.unit')}}</span>
          </span>
          <span class="span-box"
                v-else-if="scriptItem.text==='utilizationHigher'"><span>{{$t('custom.bots.utilization2')}}{{inputValue}}{{$t('custom.bots.unit')}}</span></span>
          <span class="span-box"
                style="display:flex;justify-content:space-between;align-items:center;"
                v-else-if="scriptItem.text==='scheduleTemplate'">
            <span>{{scriptItem.label}}</span>
            <div style="display:flex;justify-content:space-between;align-items:center;">
              <div>
                <el-select v-model="scheduleTimeZoneId"
                          filterable
                          clearable
                          default-first-option
                          @change="changeTimeZone"
                          class="selected-input">
                            <el-option v-for="item in timezoneList"
                                      :key="item"
                                      :label="item"
                                      :value="item">
                            </el-option>
                </el-select>
              </div>
              <el-popover placement="bottom"
                          width="500"
                          v-model="holidayVisible">
                <div style="padding:10px 0 30px;font-weight:bold;font-size:16px">Settings</div>
                <div v-loading="loading">
                  <div style="padding:0 0 50px;display:flex;align-items:center">
                    <span style="margin-right:10px">Exclude Holidays</span>
                    <el-cascader :options="options"
                                 style="width:70%"
                                 v-model="holidaysList"
                                 :props="{ multiple: true }"
                                 :show-all-levels="false"
                                 collapse-tags
                                 filterable
                                 clearable></el-cascader>
                  </div>
                  <div style="text-align: right; margin: 0">
                    <el-button size="small"
                               type="info"
                               @click="holidayVisible=false">{{$t('holidays.cancel')}}</el-button>
                    <el-button size="small"
                               type="primary"
                               @click="setHoliday">{{$t('holidays.save')}}</el-button>
                  </div>
                </div>
                <i class="el-icon-setting"
                   slot="reference"
                   style="font-size:24px;padding:0 0 0 20px;"></i>
              </el-popover>
            </div>
          </span>
          <span v-else
                class="span-box">
            <span>{{scriptItem.label}}</span>
            <TypeLabelTips v-if="scriptItem.labelTips"
                           :scriptItem='scriptItem'
                           :dataForm='dataForm' />
          </span>
          <span v-if="scriptItem.taskHoursSetting&&psa === 'Autotask'">
            <el-popover
              placement="bottom"
              width="500"
              trigger="manual"
              v-model="taskHoursVisible"
              popper-class="taskHoursPopover"
              >
              <div>
                <div style="padding:12px 12px;font-weight:bold;font-size:16px;border-bottom: 1px solid #ebebeb;color: #1b1b1b;">Settings</div>
                <div style="display: flex; align-items: center;justify-content: space-between;padding:12px 12px;">
                  <div>
                    <h3 style="color: #1b1b1b;">Includes Task Hours in Utilization</h3>
                    <p style="color:#8d8d8d">Utilization calculation is including hours spent on tasks of AutoTask.</p>
                  </div>
                  <el-switch
                    active-color="#0063e4"
                    v-model="taskHoursAutoTaskSwitch"
                   >
                  </el-switch>
                </div>
                <div style="text-align: right;padding:12px 12px; margin-top: 10px;border-top: 1px solid #ebebeb;">
                    <el-button size="small"
                               @click="taskHoursVisible =false"
                               >{{$t('holidays.cancel')}}</el-button>
                    <el-button size="small"
                               type="primary"
                               style="background-color: #0063e4"
                               @click="setTaskHoursSetting"
                              >{{$t('holidays.save')}}</el-button>
                  </div>
              </div>
              <i class="el-icon-setting" slot="reference"  style="font-size:24px;float: right;"  @click="taskHoursVisible = !taskHoursVisible"></i>
            </el-popover>
          </span>
        </span>
        <TypeSwitch v-if="scriptItem.type === 'switch'"
                    :dataForm='dataForm'
                    :scriptItem='scriptItem' />
        <TypeSwitchCondition v-if="scriptItem.type === 'switch-condition'"
                             :dataForm='dataForm'
                             :scriptItem='scriptItem' />
        <TypeText v-if="scriptItem.type === 'text'"
                  :dataForm='dataForm'
                  :scriptItem='scriptItem' />
        <TypeTextarea v-if="scriptItem.type === 'textarea'"
                      :blockInfo='blockInfo'
                      :dataForm='dataForm'
                      :scriptItem='scriptItem' />
        <TypeSelect v-if="scriptItem.type === 'select'"
                    :dataForm='dataForm'
                    :scriptItem='scriptItem' />
        <TypeSelectTemplate v-if="scriptItem.type === 'select-details'"
                            :dataForm='dataForm'
                            :scriptItem='scriptItem' />
        <TypeCustomizedSelect v-if="scriptItem.type === 'customized-select'"
                              :dataForm='dataForm'
                              :scriptItem='scriptItem' />
        <TypeCustomizedCheckboxSelect v-if="scriptItem.type === 'customized-checkbox-select'"
                                      :dataForm='dataForm'
                                      :scriptItem='scriptItem' />
        <TypeAutocomplete v-if="scriptItem.type === 'autocomplete'"
                          :dataForm='dataForm'
                          :scriptItem='scriptItem' />
        <TypeCustomizedAutocomplete v-if="scriptItem.type === 'customized-autocomplete'"
                                    :dataForm='dataForm'
                                    :scriptItem='scriptItem' />
        <TypeFilters v-if="scriptItem.type === 'filters'"
                     :dataForm='dataForm'
                     :scriptItem='scriptItem'
                     ref="type_filters" />

        <TypesSchedule v-if="scriptItem.type === 'schedule'"
                       :dataForm='dataForm'
                       :scriptItem='scriptItem'></TypesSchedule>
        <TypeSendFilter v-if="scriptItem.type ==='sendfilter'"
                        :dataForm='dataForm'
                        :scriptItem='scriptItem'></TypeSendFilter>
        <TypeTemplate v-if="scriptItem.type ==='select-template'"
                      :dataForm='dataForm'
                      :blockInfo='blockInfo'
                      :scriptItem='scriptItem'></TypeTemplate>
        <TypeToAddress v-if="scriptItem.type ==='to-address'"
                       :dataForm='dataForm'
                       :scriptItem='scriptItem'
                       ref="to-address">
        </TypeToAddress>
        <TypeTableTree v-if="scriptItem.type ==='table-tree'"
                       :dataForm='dataForm'
                       :scriptItem='scriptItem'>
        </TypeTableTree>
        <TypeTemplateMultiple v-if="scriptItem.type ==='template-multiple'"
                              ref="template-multiple"
                              :dataForm='dataForm'
                              :scriptItem='scriptItem'>
        </TypeTemplateMultiple>
        <TypeFilter v-if="scriptItem.type ==='filter'"
                    class="filter"
                    ref="type_filter"
                    :dataForm='dataForm'
                    :scriptItem='scriptItem'>
          <PreWiewData v-if="scriptItem.showPreWiewData"
                       @requstFilterSql="transmitRes"
                       slot="PreWiewData"
                       style="margin-left:20px"
                       :dataForm='dataForm'
                       :scriptItem='scriptItem'
                       :showJson='showJson'></PreWiewData>
        </TypeFilter>
        <botQuery v-if="scriptItem.type ==='botQuery'"
                  ref="botQuery"
                  @change="changeBot"
                  :dataForm='dataForm'
                  :opt='scriptItem'>
        </botQuery>
        <PreWiewData @requstFilterSql="transmitRes"
                     :dataForm='dataForm'
                     :scriptItem='scriptItem'
                     :showJson='showJson'
                     v-if="scriptItem.type ==='prewiew-data'"></PreWiewData>
        <TypeExecutionFrequency v-if="scriptItem.type ==='frequency'"
                                ref="type_frequency"
                                :dataForm='dataForm'
                                :scriptItem='scriptItem'>
        </TypeExecutionFrequency>
        <TypeLayout v-if="scriptItem.type ==='layout'"
                    :blockInfo='blockInfo'
                    :dataForm='dataForm'
                    :scriptItem='scriptItem'>
          <template v-slot:layout>
            <slot name="layout"></slot>
          </template>
        </TypeLayout>
        <TypeRadioSelect v-if="scriptItem.type ==='radio-select'"
                         :dataForm='dataForm'
                         :scriptItem='scriptItem'>
        </TypeRadioSelect>
        <TypePreviewButton v-if="scriptItem.type ==='preview-button'"
                           :dataForm='dataForm'
                           :scriptItem='scriptItem'>
        </TypePreviewButton>
        <TypeScheduleTemplate v-if="scriptItem.type ==='schedule-template'"
                              :dataForm='dataForm'
                              :scriptItem='scriptItem'>
        </TypeScheduleTemplate>
        <TypeScheduleFixRate v-if="scriptItem.type ==='schedule-fix-rate'"
                             :dataForm='dataForm'
                             :scriptItem='scriptItem'>
        </TypeScheduleFixRate>
        <TypeCycleMultipleTemplate v-if="scriptItem.type ==='cycle-multiple-template'"
                                   :dataForm='dataForm'
                                   :blockInfo='blockInfo'
                                   :scriptItem='scriptItem'>
        </TypeCycleMultipleTemplate>
        <TypeCycleLabelMultipleTemplate v-if="scriptItem.type ==='cycle-label-multiple-template'"
                                        :dataForm='dataForm'
                                        :blockInfo='blockInfo'
                                        :scriptItem='scriptItem'>
        </TypeCycleLabelMultipleTemplate>
        <TypeLabelMultiple v-if="scriptItem.type ==='label-multiple'"
                           :dataForm='dataForm'
                           :blockInfo='blockInfo'
                           @hiddenSettingModel="hiddenSettingModels"
                           :scriptItem='scriptItem'>
        </TypeLabelMultiple>
        <TypeSendMessage v-if="scriptItem.type ==='send-message'"
                         :dataForm='dataForm'
                         :scriptItem='scriptItem'>
        </TypeSendMessage>
        <TypeSendMessageBcc v-if="scriptItem.type ==='send-message-bcc'"
                            :dataForm='dataForm'
                            :scriptItem='scriptItem'>
        </TypeSendMessageBcc>
        <TypeSelectUserColumn v-if="scriptItem.type === 'select-user-column'"
                              :dataForm='dataForm'
                              :scriptItem='scriptItem' />
        <TypeSelectTree v-if="scriptItem.type ==='select-tree'"
                        :dataForm='dataForm'
                        :scriptItem='scriptItem'>
        </TypeSelectTree>
        <TypeIntegrationTrigger v-if="scriptItem.type ==='integration-trigger'"
                                :dataForm='dataForm'
                                :scriptItem='scriptItem'>
        </TypeIntegrationTrigger>
        <TypeBlockIntrol v-if="scriptItem.type ==='block-introl'"
                         :dataForm='dataForm'
                         :scriptItem='scriptItem'>
        </TypeBlockIntrol>
        <TypeUsersList v-if="scriptItem.type ==='query-select-users'"
                       :dataForm='dataForm'
                       :scriptItem='scriptItem'>
        </TypeUsersList>
        <TypeRadioGrounp v-if="scriptItem.type ==='tadio-group'"
                         :dataForm='dataForm'
                         :scriptItem='scriptItem'>
        </TypeRadioGrounp>
        <TypeRoleList v-if="scriptItem.type ==='query-select-role'"
                      :dataForm='dataForm'
                      :scriptItem='scriptItem'>
        </TypeRoleList>
        <TypeMultipleSelect v-if="scriptItem.type === 'multiple-select'"
                            :dataForm='dataForm'
                            :scriptItem='scriptItem' />
        <TypeCardJson v-if="scriptItem.type === 'type-card-json'"
                      @hiddenSettingModel="hiddenSettingModels"
                      :dataForm='dataForm'
                      :scriptItem='scriptItem' />
        <TypeCardTeamsLinkButton v-if="scriptItem.type === 'type-card-teams-link-button'"
                                 :dataForm='dataForm'
                                 :scriptItem='scriptItem' />
        <TypePostman v-if="scriptItem.type === 'postman'"
                     :dataForm='dataForm'
                     :scriptItem='scriptItem' />
        <TypeOpenai v-if="scriptItem.type === 'openai'"
                     :dataForm='dataForm'
                     :scriptItem='scriptItem' />
      </el-form-item>
      <!-- It is test component -->
      <!-- <el-form-item :key="
                          988548756"
                          :label="testData.label">
            <TypeFilters :dataForm='dataForm'
                         :scriptItem='testData' />
      </el-form-item> -->
    </el-form>
  </div>
</template>

<script>
import TypeBlockIntrol from './components/type-block-introl'
import TypeSwitch from './components/type-switch'
import TypeSwitchCondition from './components/type-switch-conditions'
import TypeText from './components/type-text'
import TypeTextarea from './components/type-textarea'
import TypeSelect from './components/type-select'
import TypeCustomizedSelect from './components/type-customized-select'
import TypeCustomizedCheckboxSelect from './components/type-customized-checkbox-select'
import TypeAutocomplete from './components/type-autocomplete'
import TypeCustomizedAutocomplete from './components/type-customized-autocomplete'
import TypeFilters from './components/type-filters'
import TypeSelectTemplate from './components/type-select-details'
import TypesSchedule from './components/type-schedule'
import TypeSendFilter from './components/type-send-filters'
import TypeTemplate from './components/type-select-template'
import TypeToAddress from './components/type-to-address'
import TypeTableTree from './components/type-table-tree'
import TypeTemplateMultiple from './components/type-template-multiple'
import TypeFilter from './components/type-filter'
import TypeExecutionFrequency from './components/type-execution-frequency'
import TypeLayout from './components/type-layout'
import TypeRadioSelect from './components/type-radio-select'
import TypePreviewButton from './components/type-preview-button'
import TypeScheduleTemplate from './components/type-schedule-template'
import TypeScheduleFixRate from './components/type-schedule-fix-rate'
import TypeLabelTips from './components/type-label-tips'
import TypeCycleMultipleTemplate from './components/type-cycle-multiple-template'
import TypeCycleLabelMultipleTemplate from './components/type-cycle-label-multiple-template'
import TypeLabelMultiple from './components/type-label-multiple'
import TypeSendMessage from './components/type-send-message'
import TypeSendMessageBcc from './components/type-send-message-bcc'
import TypeSelectUserColumn from './components/type-select-user-column'
import PreWiewData from './components/type-preview-data'
import TypeSelectTree from './components/type-select-tree'
import TypeIntegrationTrigger from './components/type-Intergration-trigger'
import TypeUsersList from './components/type-user-list'
import TypeRadioGrounp from './components/type-radio-group'
import TypeRoleList from './components/type-role-list'
import TypeMultipleSelect from './components/type-multiple-select'
import TypeCardJson from './components/type-card/type-card-teams-basic'
import TypeCardTeamsLinkButton from './components/type-card/type-card-teams-link-button'
import TypeNumberInput from './components/type-number-input'
import TypePostman from './components/type-postman'
import TypeOpenai from './components/type-openai'
import botQuery from '@/components/query-builder/bot-query'
import { TimeZoneNameList } from '@/utils'
import moment from 'moment'
export default {
  components: {
    TypeBlockIntrol,
    TypeRadioGrounp,
    TypeUsersList,
    TypeSwitch,
    TypeText,
    TypeTextarea,
    TypeSelect,
    TypeCustomizedSelect,
    TypeAutocomplete,
    TypeCustomizedAutocomplete,
    TypeFilters,
    TypeSelectTemplate,
    TypesSchedule,
    TypeSendFilter,
    TypeTemplate,
    TypeToAddress,
    TypeTableTree,
    TypeTemplateMultiple,
    TypeFilter,
    TypeExecutionFrequency,
    TypeLayout,
    TypeRadioSelect,
    TypePreviewButton,
    TypeScheduleTemplate,
    TypeScheduleFixRate,
    TypeLabelTips,
    TypeCycleMultipleTemplate,
    TypeLabelMultiple,
    TypeSendMessage,
    TypeSelectUserColumn,
    PreWiewData,
    TypeSelectTree,
    TypeIntegrationTrigger,
    TypeCustomizedCheckboxSelect,
    TypeSendMessageBcc,
    TypeSwitchCondition,
    TypeRoleList,
    TypeMultipleSelect,
    TypeCardJson,
    TypeCardTeamsLinkButton,
    TypeCycleLabelMultipleTemplate,
    TypeNumberInput,
    TypePostman,
    botQuery,
    TypeOpenai
  },
  props: {
    blockInfo: {
      type: Object,
      default: () => {
      }
    },
    showJson: {
      type: Array,
      default: () => {
        return []
      }
    },
    dataForm: {
      type: [Object, Array],
      default: () => {
      }
    },
    psa: {
      type: String,
      default: ''
    },
  },
  data () {
    return {
      holidayVisible: false,
      loading: false,
      holidaysList: [],
      options: [],
      scheduleTimeZoneId: null,
      timezoneList: [],
      taskHoursVisible: false,
      taskHoursAutoTaskSwitch: false,
    }
  },
  watch: {
    holidayVisible (val) {
      if (val) {
        this.getHolidayList()
      }
    },
    taskHoursVisible (val) {
      if (val) {
        this.taskHoursAutoTaskSwitch = this.dataForm.taskHoursAutoTaskSetting?this.dataForm.taskHoursAutoTaskSetting:false
      }
    },
  },
  created () {
    this.timezoneList = TimeZoneNameList()
    this.scheduleTimeZoneId = this.dataForm.scheduleTemplate&&this.dataForm.scheduleTemplate.timezoneid?this.dataForm.scheduleTemplate.timezoneid:this.$store.state.user.timezoneId
    this.$set(this.dataForm.scheduleTemplate, 'timezoneid', this.scheduleTimeZoneId)
    this.$set(this.dataForm.scheduleTemplate, 'timezoneoffset', moment.tz(this.scheduleTimeZoneId).format('Z'))
  },
  computed: {
    labelWidth () {
      try {
        return Number(this.scriptItem.labelWidth) + 'px'
      } catch (error) {
        return '120px'
      }
    },
    labelPosition () {
      try {
        return this.scriptItem.labelPosition || false
      } catch (error) {
        return false
      }
    },
    inputValue () {
      return this.showJson.find(v => v.text === 'indicator') ? this.dataForm[this.showJson.find(v => v.text === 'indicator').text] : ''
    },
    inputObj () {
      return this.showJson.find(v => v.text === 'indicator') || {}
    }
  },
  methods: {
    changeTimeZone (val){
      this.$set(this.dataForm.scheduleTemplate, 'timezoneid', val)
      this.$set(this.dataForm.scheduleTemplate, 'timezoneoffset', moment.tz(val).format('Z'))
    },
    async getHolidayList () {
      this.holidaysList = this.dataForm.festivals ? this.dataForm.festivals.map(v => {
        return [v.parentId, v.id]
      }) : []
      if (this.options.length) return
      this.loading = true
      const params = {
        businessType: 'Custom'
      }
      const { data: res } = await this.$interface.taskManager.holidayTree(params)
      if (res.code !== 0) {
        this.loading = false
        return this.$message.error(res.message)
      }
      res.data.sort((a, b) => a.name.localeCompare(b.name))
      res.data.forEach(v => v.festivalList.sort((a, b) => a.name.localeCompare(b.name)))
      this.options = res.data.map(v => {
        return {
          label: v.name,
          value: v.id,
          children: v.festivalList.map(v => {
            return {
              label: v.name,
              value: v.id
            }
          })
        }
      })
      this.loading = false
    },
    setHoliday () {
      this.dataForm.festivals = this.holidaysList.map(v => {
        return {
          parentId: v[0],
          id: v[1]
        }
      })
      this.holidayVisible = false
    },
    setTaskHoursSetting () {
      this.dataForm.taskHoursAutoTaskSetting = this.taskHoursAutoTaskSwitch
      console.log(this.dataForm,"this.dataForm");
      this.taskHoursVisible = false
    },
    changeBot (val) {
      this.dataForm = val
      this.$emit('test', val)
    },
    hiddenSettingModels () {
      this.$emit('hiddenSettingModel')
    },
    transmitRes () {
      this.$emit('transmitFilterSqlRes')
    },
    validateRules () {
      let temp = this.$refs['dataForm'].map(e => {
        return e.validate()
      })
      return Promise.all([...temp])
    },
    toAddressDataValidate () {
      let temp = this.$refs['to-address']
      if (!temp) {
        return true
      }
      if (temp.findIndex(e => !e.getInputValue()) < 0) {
        return true
      } else {
        return false
      }
    },
    templateMultipleDataValidate () {
      let temp = this.$refs['template-multiple']
      if (!temp) {
        return true
      }
      if (temp.findIndex(e => !e.dataValidate()) < 0) {
        return true
      } else {
        return false
      }
    },
    fliterDataValidate (from) {
      let temp = this.$refs['type_filter']
      if (!temp) {
        return true
      }
      if (temp.findIndex(e => !e.checkdataArr(from)) < 0) {
        return true
      } else {
        return false
      }
    },
    checkDataFilter () {
      return this.$refs.type_filters[0].checkRules()
    }
  }
}
</script>

<style lang='scss'>
.script_render {
  .el-form-item__label {
    line-height: 0;
    width: 100%;
    margin-bottom: 0px !important;
  }
}
.previewButton {
  line-height: 0;
  .el-form-item__label {
    padding: 0;
  }
}
.alert {
  margin-left: 60px;
}
.escalationCycle {
  display: block !important;
  .el-form-item__label {
    width: auto !important;
    font-weight: normal !important;
  }
}
.sendMessage {
  // display: flex;
  // justify-content: flex-start;
  // align-items: center;
  // ::v-deep.el-form-item__content{
  //   flex: 1;
  // }
  // ::v-deep.el-form-item__label{
  //   width: 55px;
  // }
}
.chatForm {
}
.span-box {
  span {
    font-size: 16px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.75);
    line-height: 22px;
    display: inline-block;
  }
}
.taskHoursPopover {
  padding: 0 !important;
}
</style>
